﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TeamWork_Server.HTTP
{
    public class FileTransfer
    {
        TWServerConfiguration config;
        public CodeUpdateService cus;

        public FileTransfer(TWServerConfiguration sconfig)
        {
            config = sconfig;
            cus = new CodeUpdateService();
        }

        public void service_HttpContextReceived(object sender, HttpContextReceivedEventArgs e)
        {
            try
            {
                StreamReader reader = new StreamReader(e.Context.Request.InputStream);
                string l = reader.ReadLine();
                if (e.Context.Request.HttpMethod == "POST")
                {
                    if (l.Contains("/download"))
                    {
                        string fname = l.Replace("/download ", "");
                        Log.Info(fname);
                        StreamWriter writer = new StreamWriter(e.Context.Response.OutputStream);
                        writer.WriteLine(config.GetFileText(fname));
                        writer.Flush();
                        Log.Info("Sent file '" + fname + "' to a client.");
                        writer.Close();
                    }

                }
                else
                {
                    if (e.Context.Request.Headers["TYPE"] == "GetFiles")
                    {
                        StreamWriter writer = new StreamWriter(e.Context.Response.OutputStream);
                        string data = "";
                        foreach (string n in config.Files)
                        {
                            data += config.GetFileName(n) + ";";
                        }
                        writer.WriteLine(data);
                        writer.Flush();
                        writer.Close();
                        Log.Info("Sending File Names to client.");
                    }
                }
                //cus.service_HttpContextReceived(sender, e);
            }
            catch (Exception ex) {
            }
        }
    }
}
